package fr.aracore.domotique.zapi.model;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.Hashtable;

import fr.aracore.domotique.zapi.db.DBManager;
import fr.aracore.domotique.zapi.event.ZbEvent;

public class Device {
	
	
	public final static String OREGON="OS";
	public final static String OWL="WS";
	public final static String VISONIC="VS";
	public final static String REMOTE_VISONIC="VR";
	public final static String X10_SEC="XS";
	public final static String X10_ON="X10_ON";
	public final static String X10_OFF="X10_OFF";
	public final static String CHACON="CS";
	public final static String DIGIMAX_TS10="TS";
	public final static String X2D="DX";
	
	
	
	public final static String[] protocols=new String[]{OREGON,OWL,VISONIC,REMOTE_VISONIC,X10_SEC,X10_ON,X10_OFF,CHACON,DIGIMAX_TS10,X2D};
	public final static String[] names=new String[]{"Oregon","Owl","Visionic","Remote Visionic","X10 Secure",X10_ON,X10_OFF,"Chacon",DIGIMAX_TS10,"X2D"};
	
	public String type;
	public String number;

	public String lastMessage;
	
	//plusieurs sensors possible par device
	private Hashtable<String, Sensor> sensors=new Hashtable<String, Sensor>();
	
	public Device(String type,String number){
		super();
		this.type=type;
		this.number=number;
	}
	public Device(){
		super();
	}
	public String idDevice(){
		return type+number;
	}
	
	public void receiveEvent(ZbEvent event){
		System.out.println(this+" receiving event :"+event);
		this.lastMessage=event.response.message;
		updateDeviceWithEvent(event);
	}
	
	public void updateDeviceWithEvent(ZbEvent event) {
		Sensor.updateDeviceWithEvent(this, event);
	}
	

	public static Device createDeviceWithEvent(ZbEvent event){
		String type=event.id().substring(0,2);
		String number=event.id().substring(2);
		Device lcDevice=new Device(type, number);
		Sensor.addSensorsToDeviceWithEvent(lcDevice,event);
		return lcDevice;
	}
	
	public String name(){
		int lcIndex=Arrays.asList(protocols).indexOf(type);
		if (lcIndex>=0) return names[lcIndex];
		else return "Unknown";
		
	}

	public void addSensor(Sensor sensor){
		sensors.put(sensor.tag(), sensor);
	}
	
	public Sensor getSensor(String tag){
		return sensors.get(tag);
	}

	public String showTree(){
		String lcTree="\t"+toString()+"\n";
		Enumeration<Sensor> lcEnum=sensors.elements();
		while (lcEnum.hasMoreElements()){
			Sensor lcSensor=lcEnum.nextElement();
			lcTree=lcTree+"\t\t"+lcSensor.tag()+"="+lcSensor.value()+"\n";
		}
			
		return lcTree;
	}
	public String toString(){
		return super.toString()+" ("+name()+"-"+idDevice()+")";
	}
	
	
}
